/**
 * Created by apple on 2017/10/9.
 */
var express = require('express');
var router = express.Router();

var UserAgentDao = require('../dao/user_agent');
var UserToken = require('../db/user_tokens.js');
var config = require('../config');
var UserAgentRouter = module.exports;


/**
 * 管理员设置用户省级、市级代理
 * @param   token(管理员) app_sid, pre_agent_lvl(前置代理等级 只能为1-6)
 */
UserAgentRouter.setPreAgentLvl = function (req, res) {
    var par = paramAll(req);
    if(!par.uid) return res.json(new ERR('用户标识不为空', 400));
    if(!par.app_sid) return res.json(new ERR('app标识不为空', 400));
    if(isNaN(par.pre_agent_lvl)) return res.json(new ERR('代理等级有误', 400));
    if(par.pre_agent_lvl > 6 || par.pre_agent_lvl < 1) return res.json(new ERR('代理等级有误', 400));
    UserToken.checkAdminLogin(par.token,par.app_sid, function (err,errCode, loginInfo) {

        if(err) return res.json(new ERR(err, errCode));

        UserAgentDao.setPreAgentLvl(par, function (err, result) {
            if (err) {
                res.json(new ERR(err, 400));
                return;
            }
            res.json(new PKG(result));
        })
    });

}
router.post('/setPreAgentLvl', UserAgentRouter.setPreAgentLvl);

/**
 * usuz设置用户省级、市级代理
 * @param   app_sid, pre_agent_lvl(前置代理等级 只能为1-6)
 */
UserAgentRouter.setPreAgentLvlBySrv = function (req, res) {
    var par = paramAll(req);
    if(!checkSrvConnection(par)) return res.json(new ERR('访问受限',400));
    if(!par.uid) return res.json(new ERR('用户标识不为空', 400));
    if(!par.app_sid) return res.json(new ERR('app标识不为空', 400));
    if(isNaN(par.pre_agent_lvl)) return res.json(new ERR('代理等级有误', 400));
    if(par.pre_agent_lvl > 6 || par.pre_agent_lvl < 1) return res.json(new ERR('代理等级有误', 400));
    UserAgentDao.setPreAgentLvl(par, function (err, result) {
        if (err) {
            res.json(new ERR(err, 400));
            return;
        }
        res.json(new PKG(result));
    })
}
router.post('/setPreAgentLvlBySrv', UserAgentRouter.setPreAgentLvlBySrv);


/**
 * usuz查看用户信息
 * @param
 */
UserAgentRouter.getUserInfo = function (req, res) {
    var par = paramAll(req);
    if(!par.app_sid) return res.json(new ERR('app标识不为空', 400));
    // if(!par.uids) return res.json(new ERR('用户标识不为空', 400));
    // par.uids = par.uids.split(',');
    // for (var i = 0; i < par.uids.length; i++) {
    //     par.uids[i] = parseInt(par.uids[i]);
    // }
    UserToken.checkAdminAllLogin(par.token,par.app_sid,'taoke', function (err,errCode, loginInfo) {

        if(err) return res.json(new ERR(err, errCode));

        UserAgentDao.getUserInfo(par, function (err, result) {
            if (err) {
                res.json(new ERR(err, 400));
                return;
            }
            res.json(new PKG(result));
        })
    });

}
router.post('/getUserInfo', UserAgentRouter.getUserInfo);


/**
 * usuz查看用户代理信息
 * @param   app_sid
 * @param   token
 * @param   wx_unionid   (token  | wx_unionid  必传之一)
 */
UserAgentRouter.getUserAgent = function (req, res) {
    var par = paramAll(req);
    if(!par.app_sid) return res.json(new ERR('app标识不为空', 400));
    if(!par.token && !par.wx_unionid) return res.json(new ERR('缺少必要参数', 400));
    if(par.token) {
        UserToken.checkLogin(par.token,function (err,userInfo) {
            if(err) return res.json(new ERR(err, 400));
            if(!userInfo) return res.json(new ERR(err, 403));
            par.uid = userInfo.uid;
            UserAgentDao.getUserAgent(par, function (err, result) {
                if (err) {
                    return res.json(new ERR(err, 400));
                }
                result.recommendCode = uidToCode(par.uid);
                res.json(new PKG(result));
            });

        });
    } else if(par.wx_unionid) {
        UserAgentDao.getUidByWxunionid(par, function(e, r) {
            if(e) {
                return res.json(new ERR(e, 400));
            } else if(r && r[0] && r[0].uid != undefined){
                par.uid = r[0].uid;
                UserAgentDao.getUserAgent(par, function (err, result) {
                    if (err) {
                        return res.json(new ERR(err, 400));
                    }
                    result.recommendCode = uidToCode(par.uid);
                    res.json(new PKG(result));
                });
            } else {
                return res.json(new ERR('还未绑定手机号码，请先绑定手机号码', 400));
            }
        });
    }

}
router.post('/getUserAgent', UserAgentRouter.getUserAgent);

/**
 * 添加用户设备信息
 * @param
 */
UserAgentRouter.addUserUUID = function (req, res) {
    var par = paramAll(req);
    if(!par.uuid) return res.json(new ERR('uuid不为空', 400));
    UserToken.checkLogin(par.token,function (err,userInfo) {
        if(err) return res.json(new ERR(err, 400));
        if(!userInfo) return res.json(new ERR(err, 403));
        par.uid = userInfo.uid;
        par.account = userInfo.account;
        UserAgentDao.addUserUUID(par, function (err, result) {
            if (err) {
                res.json(new ERR(err, 400));
                return;
            }
            res.json(new PKG(result));
        });

    });
}
router.post('/addUserUUID', UserAgentRouter.addUserUUID);

/**
 * 获取有效用户数
 * @param
 */
UserAgentRouter.getLoginSubNum = function (req, res) {
    var par = paramAll(req);
    UserToken.checkLogin(par.token,function (err,userInfo) {
        if(err) return res.json(new ERR(err, 400));
        if(!userInfo) return res.json(new ERR(err, 403));
        par.account = userInfo.account;
        UserAgentDao.findLoginSubNum(par, function (err, result) {
            if (err) {
                res.json(new ERR(err, 400));
                return;
            }
            res.json(new PKG(result));
        });

    });
}
router.post('/getLoginSubNum', UserAgentRouter.getLoginSubNum);

/**
 * 管理员更改用户推荐人
 * @param   token(管理员的token)
 * @param   account(修改用户的account)
 * @param   new_recommender(修改用户的新推荐人)
 * @param   old_recommender(修改用户的旧推荐人)
 */
UserAgentRouter.changeRecommender = function (req, res) {
    var par = paramAll(req);
    if (!par.account) return res.json(new ERR('账号不为空', 400));
    if (!par.new_recommender) return res.json(new ERR('新推荐人不为空', 400));
    if (!par.old_recommender) return res.json(new ERR('旧推荐人不为空', 400));
    if (par.new_recommender == par.old_recommender) return res.json(new ERR('推荐人一致，无需修改', 400));
    UserToken.checkAdminLogin(par.token,par.app_sid, function (err,errCode, loginInfo) {

        if(err) return res.json(new ERR(err, errCode));

        UserAgentDao.changeRecommender(par, function (err, result) {
            if (err) {
                res.json(new ERR(err, 400));
                return;
            }
            res.json(new PKG(result));
        })
    });

}
router.post('/changeRecommender', UserAgentRouter.changeRecommender);

/**
 * 存wxid和app_sid的接口
 * userAgent/saveWxRecInfo (没有)
 * 参数：code(微信唯一标识)、app_sid、recommendCode, code_type
 */
UserAgentRouter.saveWxRecInfo = function (req, res) {
    var par = paramAll(req);
    if (!par.app_sid) return res.json(new ERR('产品标识不为空', 400));
    if (!par.code) return res.json(new ERR('code不为空', 400));
    if (!par.code_type) return res.json(new ERR('code类型不为空', 400));
    if (!par.recommendCode) return res.json(new ERR('推荐码不为空', 400));
    par.recommendUid = codeToUid(par.recommendCode) == false ? 1 : codeToUid(par.recommendCode);
    delete par.recommendCode;
    if (par.min_pro) {
        UserAgentDao.getMinProWXunionid(par, function(e, unionid) {
            if(e) {
                if(e.status == 405) {
                    return res.json(new ERR({isVisitor: true}, 405));
                }
                return res.json(new ERR(e, 400));
            } else {
                par.wx_unionid = unionid.unionid;
                var info = {};
                info.wx_unionid = par.wx_unionid;
                info.wx_nick = unionid.nickname ? unionid.nickname : null;
                info.wx_avatar = unionid.headimgurl ? unionid.headimgurl : null;
                info.passVersion = config.minPro_passVersion[par.code_type];
                info.openid = unionid.openid;
                doSaveWxRecInfo(info, par, res);
            }
        });
    } else {
        UserAgentDao.getWXunionid(par, function(e, unionid) {
            if(e) {
                return res.json(new ERR(e, 400));
            } else {
                par.wx_unionid = unionid.unionid;
                var info = {};
                info.wx_unionid = par.wx_unionid;
                info.wx_nick = unionid.nickname ? unionid.nickname : null;
                info.wx_avatar = unionid.headimgurl ? unionid.headimgurl : null;
                info.openid = unionid.openid;
                doSaveWxRecInfo(info, par, res);
            }
        });
    }
}
function doSaveWxRecInfo(info, par, res) {
    UserAgentDao.saveWxRecInfo(par, function (err, result) {
        if (err) {
            res.json(new ERR(err, 400));
            return;
        }
        var canBind = result && result.canBind ? true : false;
        info.canBind = canBind;
        if(canBind == false) {
            if(info.wx_unionid && info.wx_avatar && info.wx_nick) UserAgentDao.saveWxInfo(info, function() {});
            UserToken.onLogin(result, function (err, data) {
                if(err) return res.json(new ERR(err, 400));
                info.token = data;
                if (result && result.uid) {
                    info.recommendCode = uidToCode(result.uid);
                    info.uid = result.uid;
                }
                res.json(new PKG(info));
            });
        } else {
            if (result.recommendUid) info.original_rc = uidToCode(result.recommendUid);
            res.json(new PKG(info));
        }
    });
}
router.post('/saveWxRecInfo', UserAgentRouter.saveWxRecInfo);

UserAgentRouter.getUserInfoByCode = function (req, res) {
    var par = paramAll(req);
    if (!par.app_sid) return res.json(new ERR('产品标识不为空', 400));
    if (!par.code) return res.json(new ERR('code不为空', 400));
    if (!par.code_type) return res.json(new ERR('code类型不为空', 400));
    UserAgentDao.getWXunionid(par, function(e, unionid) {
        if(e) {
            return res.json(new ERR(e, 400));
        } else {
            par.wx_unionid = unionid.unionid;
            var info = {};
            info.wx_unionid = par.wx_unionid;
            info.wx_nick = unionid.nickname ? unionid.nickname : null;
            info.wx_avatar = unionid.headimgurl ? unionid.headimgurl : null;
            info.openid = unionid.openid;
            info.app_sid = par.app_sid;
            doGetWXinfo(info, par, res);
        }
    });
};
router.post('/getUserInfoByCode', UserAgentRouter.getUserInfoByCode);

function doGetWXinfo (info,par,res) {
    UserAgentDao.getInfoByWX(info, function (err, result) {
        if (err) {
            res.json(new ERR(err, 400));
            return;
        }
        var canBind = result && result.canBind ? true : false;
        info.canBind = canBind;
        var userInfo = result.userInfo;
        if(canBind == false) {
            if(info.wx_unionid && info.wx_avatar && info.wx_nick) UserAgentDao.saveWxInfo(info, function() {});
            info.account = userInfo.account;
            info.uid = userInfo.uid;
            info.pre_agent_lvl = userInfo.pre_agent_lvl;
            UserToken.onLogin(info, function (err, data) {
                if(err) return res.json(new ERR(err, 400));
                info.token = data;
                if (info.uid) info.recommendCode = uidToCode(info.uid);
                res.json(new PKG(info));
            });
        } else {
            if (userInfo.recommendUid) info.original_rc = uidToCode(userInfo.recommendUid);
            res.json(new PKG(info));
        }
    });
}

/**
 * 获得wxunionid等信息
 * userAgent/getWXunionid (没有)
 * 参数：code(微信唯一标识)、app_sid  code_type
 */
UserAgentRouter.getWXunionid = function (req, res) {
    var par = paramAll(req);
    if (!par.app_sid) return res.json(new ERR('产品标识不为空', 400));
    if (!par.code) return res.json(new ERR('code不为空', 400));
    if (!par.code_type) return res.json(new ERR('code_type不为空', 400));
    if (par.recommendCode) par.recommendUid = codeToUid(par.recommendCode) == false ? 1 : codeToUid(par.recommendCode);
    if (par.min_pro) {
        UserAgentDao.getMinProWXunionid(par, function(e, unionid) {
            if(e) {
                return res.json(new ERR(e, 400));
            } else {
                res.json(new PKG(unionid));
            }
        });
    } else {
        UserAgentDao.getWXunionid(par, function(e, unionid) {
            if(e) {
                return res.json(new ERR(e, 400));
            } else {
                res.json(new PKG(unionid));
            }
        });
    }
}
router.post('/getWXunionid', UserAgentRouter.getWXunionid);

/**
 * 查看用户推荐情况
 * userAgent/getInviteDoneStatus
 * 参数：app_sid token、(invite_done)
 */
UserAgentRouter.getInviteDoneStatus = function (req, res) {
    var par = paramAll(req);
    if (!par.app_sid) return res.json(new ERR('产品标识不为空', 400));
    UserToken.checkLogin(par.token, function (err, userInfo) {
        if (err) return res.json(new ERR(err, 400));
        if (!userInfo) return res.json(new ERR('请先登录', 403));
        par.account = userInfo.account;
        UserAgentDao.getInviteDoneStatus(par, function (err, result) {
            if (err) {
                res.json(new ERR(err, 400));
                return;
            }
            res.json(new PKG(result));
        });
    });
}
router.post('/getInviteDoneStatus', UserAgentRouter.getInviteDoneStatus);

/**
 * 设置总监  扣除 180
 * @param   token(管理员)
 * @param   app_sid
 * @param   account
 * @param   reduce_money    (180)  可自定义
 *          url/userAgent/setDirector
 */
UserAgentRouter.setDirector = function (req, res) {
    var par = paramAll(req);
    if(!par.app_sid) return res.json(new ERR('app标识不为空', 400));
    if(!par.account) return res.json(new ERR('account不为空', 400));
    if(par.reduce_money == undefined) return res.json(new ERR('reduce_money不为空', 400));
    if(isNaN(par.reduce_money)) return res.json(new ERR('reduce_money为数值类型', 400));
    if(par.token) {
        UserToken.checkAdminLogin(par.token,par.app_sid, function (err,errCode, loginInfo) {
            if(err) return res.json(new ERR(err, errCode));
            UserAgentDao.setDirector(par, function (err, result) {
                if (err) {
                    res.json(new ERR(err, 400));
                    return;
                }
                res.json(new PKG(result));
            })
        });
    } else {
        if(!checkSrvConnection(par)) return res.json(new ERR('访问受限',400));
        UserAgentDao.setDirector(par, function (err, result) {
            if (err) {
                res.json(new ERR(err, 400));
                return;
            }
            res.json(new PKG(result));
        })
    }

}
router.post('/setDirector', UserAgentRouter.setDirector);

/**
 * 设置微淘客  扣除 180
 * @param     token(管理员)
 * @param     app_sid
 * @param     account
 * @param     reduce_money    (180)  可自定义
 *            url/userAgent/setJihuo
 */
UserAgentRouter.setJihuo = function (req, res) {
    var par = paramAll(req);
    if(!par.app_sid) return res.json(new ERR('app标识不为空', 400));
    if(!par.account) return res.json(new ERR('account不为空', 400));
    if(par.reduce_money == undefined) return res.json(new ERR('reduce_money不为空', 400));
    if(isNaN(par.reduce_money)) return res.json(new ERR('reduce_money为数值类型', 400));
    UserToken.checkAdminLogin(par.token,par.app_sid, function (err,errCode, loginInfo) {

        if(err) return res.json(new ERR(err, errCode));

        UserAgentDao.setJihuo(par, function (err, result) {
            if (err) {
                res.json(new ERR(err, 400));
                return;
            }
            res.json(new PKG(result));
        })
    });

}
router.post('/setJihuo', UserAgentRouter.setJihuo);

/**
 * 保存微信昵称和头像
 * @param     wx_nick
 * @param     wx_avatar
 * @param     wx_unionid
 *            url/userAgent/saveWxInfo
 */
UserAgentRouter.saveWxInfo = function (req, res) {
    var par = paramAll(req);
    if(!par.wx_nick) return res.json(new ERR('wx_nick不为空', 400));
    if(!par.wx_avatar) return res.json(new ERR('wx_avatar不为空', 400));
    if(par.wx_unionid) return res.json(new ERR('wx_unionid不为空', 400));
    UserAgentDao.saveWxInfo(par, function (err, result) {
        if (err) {
            res.json(new ERR(err, 400));
            return;
        }
        res.json(new PKG(result));
    })
}
router.post('/saveWxInfo', UserAgentRouter.saveWxInfo);

module.exports = router;

